package fr.xebia.monitoring.appender;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import fr.xebia.monitoring.MeasureHandler;
import fr.xebia.monitoring.beans.AggregatedMeasures;
import fr.xebia.monitoring.beans.Measure;
import fr.xebia.monitoring.beans.formater.MeasureFormater;
import fr.xebia.monitoring.beans.formater.MeasureFormaterFactory;
import fr.xebia.monitoring.config.MeasureType;

/**
 * Default refresh interval is 5000 ms.
 * Default output format is CSV
 * Default measureType is aggregated
 */
public abstract class AbstractMeasureAppender implements MeasureAppender {

	protected final Logger logger = Logger.getLogger(getClass());

	private static final long DEFAULT_REFRESH_INTERVAL = 10000L;
	
	private MeasureFormater formater;
	private MeasureHandler measureHandler;
	private long refreshInterval = DEFAULT_REFRESH_INTERVAL;
	private String format;
	private MeasureType measureType = MeasureType.AGGREGATED;

	public AbstractMeasureAppender() {
		super();
	}
	
	public MeasureType getMeasureType() {
		return this.measureType;
	}

	public void setMeasureType(MeasureType measureType) {
		this.measureType = measureType;
	}

	public long getRefreshInterval() {
		return this.refreshInterval;
	}

	public void setRefreshInterval(long interval) {
		this.refreshInterval = interval;
	}

	public String getFormat() {
		return this.format;
	}

	public void setFormat(String format) {
		this.format = format;
	}

	public void setMeasureHandler(MeasureHandler measureHandler) {
		this.measureHandler = measureHandler;
	}

	protected AggregatedMeasures getAggregatedMeasures() {
		return measureHandler.getAggregatedMeasures();
	}

	protected Measure[] getMeasures() {
		return measureHandler.getMeasures();
	}

	protected MeasureFormater getFormater() {
		if (this.formater == null) {
			if (StringUtils.isEmpty(format)) {
				logger.info("No format specified, using csv as default");
				format = MeasureFormaterFactory.CSV_FORMAT;
			}
			this.formater = MeasureFormaterFactory.createFormater(format);
		}
		return this.formater;
	}

	public abstract void run();
}
